package ru.usu.gv.graph;

import ru.usu.gv.core.GraphEngine;
import ru.usu.gv.styles.StyleFacade;

import java.util.ArrayList;
import java.util.List;

/**
 @author: Sergey Pupyrev 
 Mar 26, 2006
 
 Always-directed version of graph
*/

public class Graph
{
	private List<Vertex> listVertex = new ArrayList();

	public Graph()
	{
	}

	public int getSize()
	{
		return listVertex.size();
	}

	public int getEdgeSize()
	{
		int result = 0;
		for (Vertex v : listVertex)
			result += v.getEdgesSize();

		if (!StyleFacade.isDirectedGraph())
			result /= 2;
		return result;
	}

	public Vertex getVertex(int index)
	{
		return listVertex.get(index);
	}

	public void addVertex(Vertex v)
	{
		v.setIndex(getSize());
		listVertex.add(v);
		GraphEngine.getInstance().getGraphListeners().doChange(this);
	}

	public void removeVertex(Vertex v)
	{
		int deletingIndex = v.getIndex();
		for (int i = deletingIndex + 1; i < listVertex.size(); i++)
		{
			listVertex.get(i).setIndex(i - 1);
		}
		listVertex.remove(v);
		GraphEngine.getInstance().getGraphListeners().doChange(this);
	}

	public void addEdge(Vertex v1, Vertex v2)
	{
		v1.getOutEdges().add(v2);
		v2.getInEdges().add(v1);
		GraphEngine.getInstance().getGraphListeners().doChange(this);
	}

	public void removeEdge(Vertex v1, Vertex v2)
	{
		v1.getOutEdges().remove(v2);
		v2.getInEdges().remove(v1);
		GraphEngine.getInstance().getGraphListeners().doChange(this);
	}

	public void clear()
	{
		listVertex.clear();
	}
}
